package webService;

import java.io.IOException;
import java.util.HashSet;
import java.util.Set;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import serverDB.Box;
import serverDB.Client;
import serverDB.ConnectToDataBase;
import serverDB.File;
import serverDB.Tages;

/**
 * search Tag  in the server
 * @author ran,barak
 *
 */
public class SearchServlet extends HttpServlet{
	/**
	 * Default serialVersionUID
	 */
	private static final long serialVersionUID = 1L;
	/*
	 * provide the service for all requests
	 * @see javax.servlet.http.HttpServlet#service(javax.servlet.http.HttpServletRequest, javax.servlet.http.HttpServletResponse)
	 */
	@Override
	protected void service(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {
		// get the session
		HttpSession session = req.getSession();
		Set<String> searchList = new HashSet<String>();
		// get attributes
		int numOfSearch = (Integer)session.getAttribute("numOfSearch");
		for(int i=0;i<numOfSearch;i++){
			if(req.getParameter("search"+i)!=null)
				searchList.add(req.getParameter("search"+i));
		}
		
		Set<File> returnedFiles = new HashSet<File>();
		// get the client
		Client client = (Client)session.getAttribute("client");
		ConnectToDataBase connectToDataBase = ConnectToDataBase.getInst();
		client = connectToDataBase.regetClient(client);
		// get client box
		Set<Box> boxes = client.getBoxes();
		for(Box box : boxes){
			// get the files from the box
			Set<File> files = box.getFiles();
			for(File f : files){
				// get the tags from the file
				Set<Tages> tags = f.getTages();
				for(Tages tag : tags){
					if(searchList.contains(tag.getTag())){
						returnedFiles.add(f);
						break;
					}
				}
			}
		}
		// send the result
		session.setAttribute("files", returnedFiles);
		session.setAttribute("numOfSearch", 1);
		resp.sendRedirect("showFiles.jsp");
	}
}
